package com.sebklebes.radar.widget;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.sebklebes.radar.*;
import com.sebklebes.radar.dialogs.DialogActivity;
import com.sebklebes.radar.dialogs.DialogTypes;
import com.sebklebes.radar.dialogs.DialogFactory;
import com.sebklebes.radar.radar.RadarService;

public class RadarWidget extends AppWidgetProvider {

	private static final String TAG = RadarWidget.class.getName();
	private static String WIDGET_CLICK = "com.sebklebes.radar.ACTION_WIDGET_CLICK";

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
	                     int[] appWidgetIds) {
		final int N = appWidgetIds.length;
		// Perform this loop procedure for each App Widget that belongs to this
		// provider
		for (int i = 0; i < N; i++) {
			int appWidgetId = appWidgetIds[i];

			Intent intent = new Intent(WIDGET_CLICK);
			PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
					0, intent, 0);

			// Get the layout for the App Widget and attach an on-click listener
			// to the button
			RemoteViews views = new RemoteViews(context.getPackageName(),
					R.layout.widget);
			views.setOnClickPendingIntent(R.id.widget, pendingIntent);

			// Tell the AppWidgetManager to perform an update on the current App
			// Widget
			appWidgetManager.updateAppWidget(appWidgetId, views);
		}
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		super.onReceive(context, intent);
		if (WIDGET_CLICK.equals(intent.getAction())) {
			Log.d(TAG, "Widget was clicked.");
			if (RadarService.isRunning) {
				if (RadarService.cachedLocation != null) {
					Intent intent1 = new Intent(context, DialogActivity.class);
					intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent1.putExtra(DialogFactory.DIALOGS, DialogTypes.SEND_RADAR);
					context.startActivity(intent1);
				} else {
					Toast.makeText(context, "Location not available",
							Toast.LENGTH_SHORT).show();
				}
			} else {
				Intent intent1 = new Intent(context, DialogActivity.class);
				intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent1.putExtra(DialogFactory.DIALOGS, DialogTypes.SERVICE_NOT_RUNNING);
				context.startActivity(intent1);
			}
		}
	}
}
